import React, { FC, useEffect, useState } from 'react';
import { FormInstance } from 'antd/lib/form';
import { Button, message } from 'antd';
import ProTable, { ProColumns } from '@/components/ProTable';
import useHoxModel from '../../../../useHoxModel';
import { AddDoorType } from '../../../../API';
import { useUnmount, useUpdateEffect } from 'ahooks';
import styles from './index.less';
// import { pick } from 'lodash';
import DoorToChoose from './DoorToChoose';
import IconFont from '@/components/IconFont';
// import { AreaListReturnProps } from '../../../../API';

const UserForm: FC<{
  userFormRef: React.MutableRefObject<FormInstance | undefined>;
  info: { id?: number };
  formRef?: React.MutableRefObject<FormInstance | undefined>;
}> = ({ userFormRef, info, formRef }) => {
  const {
    userFormAreaList = [],
    getUserFormAreaList,
    dispatch,
    isConfig,
    getUserList,
    cardUserListByDoor,
    userList,
  } = useHoxModel((model) => [
    model.userFormAreaList,
    model.cardUserListByDoor,
    model.formDoorList,
    model.userList,
  ]);

  const [formAreaCode, setFormAreaCode] = useState<string>('');

  useUnmount(() => {
    userFormRef.current?.resetFields();
  });
  useEffect(() => {}, []);

  useUpdateEffect(() => {
    const selectedUser = userFormRef.current?.getFieldValue('selectedUser');
    userFormRef.current?.setFieldsValue({
      selectedUser: {
        ...selectedUser,
        list: cardUserListByDoor || [],
      },
    });
  }, [cardUserListByDoor]);

  useUpdateEffect(() => {
    //根据区域获取列表
    getUserList({ code: formAreaCode, number: 9999, page: 1 });
  }, [formAreaCode]);

  useUpdateEffect(() => {
    const fields = userFormRef.current?.getFieldsValue();

    const user = fields?.user;
    userFormRef.current?.setFieldsValue({
      user: {
        ...user,
        list: userList?.list || [],
      },
    });
  }, [userList]);

  const loadData = async (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    let res = await getUserFormAreaList({ id: targetOption.value });
    if (res.result === 0) {
      targetOption.loading = false;
      targetOption.children = res?.data.map((item: any) => {
        return {
          label: item.name,
          value: item.id,
          isLeaf: item.isRegion,
          code: item.code,
        };
      });
      dispatch({ userFormAreaList });
    }
  };

  const columns: ProColumns<AddDoorType>[] = [
    {
      title: '用户区域选择:',
      dataIndex: 'regionId',
      valueType: 'cascader',
      formItemProps: {
        options: userFormAreaList,
        loadData,
        changeOnSelect: true,
        onChange: (value: any, selectedRowKeys: any) => {
          setFormAreaCode(selectedRowKeys[selectedRowKeys.length - 1].code);
          userFormRef.current?.setFieldsValue({ regionId: value });
        },
      },
    },
    {
      title: '用户选择:',
      dataIndex: 'user',
      renderFormItem: () => {
        return (
          <DoorToChoose
            checkData={(item: { id: number; name: string }) => {
              const selectedUser = userFormRef.current?.getFieldValue('selectedUser');
              const isHas = (selectedUser?.list || []).some((app: { id: number }) => {
                return app.id === item.id;
              });

              return isHas ? null : item;
            }}
          />
        );
      },
    },
    {
      key: 'button',
      renderFormItem: () => (
        <div className={styles['move']}>
          <Button
            onClick={async () => {
              const fields = userFormRef.current?.getFieldsValue();
              const user = fields?.user;
              if (!user.selectedKeys || !user.selectedKeys[0]) return;
              const selectedUserSelected = fields?.selectedUser?.selectedKeys || [];
              const selectedUser = fields?.selectedUser;
              const selectedDoor =
                (formRef && formRef?.current?.getFieldValue('selectedDoor')) || null;
              //全局权限下并且用户为空的
              if (formRef && selectedDoor && selectedDoor?.list && !selectedDoor?.list[0]) {
                const selectedUserIds =
                  selectedUser &&
                  selectedUser.list.map((item: { id: number }) => {
                    return item.id;
                  });
                userFormRef.current?.setFieldsValue({
                  selectedUser: {
                    selectedKeys: selectedUserSelected, //设置选中的数据到下面框中
                    list: (selectedUser?.list || []).concat(
                      user?.selectedKeys.filter((item: any) => {
                        return !selectedUserIds.includes(item.id);
                      }) || [],
                    ),
                  },
                  user: {
                    selectedKeys: [],
                  },
                });
              } else {
                const doorIds =
                  (selectedDoor?.list &&
                    selectedDoor.list.map((item: { id: number }) => {
                      return item.id;
                    })) ||
                  null;
                let res = await isConfig({
                  userIds: user?.selectedKeys
                    .map((item: { id: number }) => {
                      return item.id;
                    })
                    .join(','),
                  doorIds: doorIds ? doorIds.join(',') : (info?.id && info?.id.toString()) || '',
                });
                if (res.result === 0) {
                  let data = res.data;
                  const configUser = data.configUser;
                  let configUserIds = configUser.map((item: { userId: number }) => {
                    return item.userId;
                  });

                  userFormRef.current?.setFieldsValue({
                    selectedUser: {
                      selectedKeys: selectedUserSelected, //设置选中的数据到下面框中
                      list: (selectedUser?.list || []).concat(
                        user?.selectedKeys.filter((item: any) => {
                          return configUserIds.includes(item.id);
                        }) || [],
                      ),
                    },
                    user: {
                      selectedKeys: [],
                    },
                  });
                }
              }
            }}
          >
            <IconFont type={'iconyiru'} />
            <span>移入</span>
          </Button>
        </div>
      ),
    },
    {
      title: '已选用户:',
      dataIndex: 'selectedUser',
      rules: [
        {
          required: true,
        },
      ],
      renderFormItem: () => {
        return <DoorToChoose showDeleteButton />;
      },
    },
  ];

  return (
    <div className={styles['add-form']}>
      <ProTable<AddDoorType>
        form={{
          name: 'form-user',
          layout: 'vertical',
          autoComplete: 'off',
          initialValues: {
            selectedUser: {
              selectedKeys: [],
              list: [],
            },
          },
        }}
        columns={columns}
        type={'form'}
        formRef={userFormRef}
      />
    </div>
  );
};
export default UserForm;
